<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库调拨单编码" prop="transferCode">
        <el-input v-model="queryParams.transferCode" placeholder="请输入仓库调拨单编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker clearable v-model="queryParams.createDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="修改人" prop="modifyBy">
        <el-input v-model="queryParams.modifyBy" placeholder="请输入修改人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker v-model="daterangeModifyDate" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['store:transfer:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['store:transfer:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['store:transfer:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed prop="transferCode" label="调拨编号" width="150">
        <template slot-scope="scope">
          <OrderView :data="scope.row" />
        </template>
      </el-table-column>
      <el-table-column label="调出仓库名称" align="center" prop="houseOutName" />
      <el-table-column label="调入仓库名称" align="center" prop="houseInName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0" style="color: orange;">已提交</span>
          <span v-else-if="scope.row.status === 1" style="color: #409eff;">待出库</span>
          <span v-else-if="scope.row.status === 2" style="color: green;">待入库</span>
          <span v-else-if="scope.row.status === 3" style="color: red;">已完成</span>
        </template>
      </el-table-column>

      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column label="修改时间" align="center" prop="modifyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['store:transfer:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改调拨管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="调出仓库" prop="houseOutId">
          <template>
            <el-select v-model="form.houseOutId" placeholder="请选择" @change="chooseOutHouse">
              <el-option v-for="item in houseOutList" :key="item.id" :label="item.houseName" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="调入仓库" prop="houseInId" v-if="form.houseOutId > 0">
          <template>
            <el-select v-model="form.houseInId" placeholder="请选择">
              <el-option v-for="item in houseInList" :key="item.id" :label="item.houseName" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <div v-if="form.houseInId > 0">
          <el-button type="primary" @click="getGoodsListByHouseId()">添加调拨明细</el-button>
        </div>
        <div class="transfer-details-title">调拨明细</div>
        <el-form-item>
          <el-table :data="form.detailList" border width="100%">
            <el-table-column label="商品编码" align="center" prop="proCode"></el-table-column>
            <el-table-column label="商品名称" align="center" prop="proName"></el-table-column>
            <el-table-column label="商品单位" align="center" prop="unitName"></el-table-column>
            <el-table-column label="调出仓库库存" align="center" prop="stock"></el-table-column>
            <el-table-column label="调拨数量" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.goodsNum" @change="validateGoodsNum(scope.row)"
                  placeholder="请输入调拨数量"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="removeGoods(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <el-dialog :visible.sync="isGoodsList" :title="goodsTitle" width="500px" append-to-body>
        <el-table :data="goodsList" border style="width: 100%" @selection-change="getGoodsIds">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="商品编码" align="center" prop="proCode" />
          <el-table-column label="商品名称" align="center" prop="proName" />
          <el-table-column label="商品单位" align="center" prop="unitName" />
          <el-table-column label="调出仓库库存" align="center" prop="stock" />
        </el-table>
        <pagination v-show="goodsTotal > 0" :total="goodsTotal" :page.sync="warehouseGoodsDTO.pageNum"
          :limit.sync="warehouseGoodsDTO.pageSize" @pagination="getGoodsListByHouseId" />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="adddetailList()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="add()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTransfer, getGoodsListByHouseId, getAllHouseList, delTransfer, addTransfer } from "@/api/store/transfer";
import OrderView from "./OrderView.vue";
export default {
  name: "Transfer",
  components: { OrderView },
  data() {
    return {
      isUpdate: false,
      selectedGoods: [],
      goodsTitle: '选择调出商品',
      isGoodsList: false,
      outValue: '',
      inValue: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      goodsTotal: 0,
      // 调拨管理表格数据
      transferList: [],
      goodsList: [],
      // 弹出层标题
      title: "",
      houseInList: [],
      houseOutList: [],
      detailList: [],
      // 是否显示弹出层
      open: false,
      // 调入仓库id时间范围
      daterangeModifyDate: [],
      warehouseGoodsDTO: {
        houseId: '',
        pageNum: 1,
        pageSize: 10
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferCode: null,
        houseOutId: null,
        houseInId: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        transferCode: [
          { required: true, message: "仓库调拨单编码不能为空", trigger: "blur" }
        ],
        houseOutId: [
          { required: true, message: "调出仓库id不能为空", trigger: "blur" }
        ],
        houseInId: [
          { required: true, message: "调入仓库id不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createDate: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getGoodsListByHouseId() {
      if (this.form.houseOutId == '') {
        alert("请先选择调出仓库");
        return;
      }
      this.warehouseGoodsDTO.houseId = this.form.houseOutId;
      getGoodsListByHouseId(this.warehouseGoodsDTO).then(res => {
        this.goodsTotal = res.total;
        this.goodsList = res.rows;
        this.isGoodsList = true;
      })

    },
    //校验输入数量
    validateGoodsNum(row) {
      const goodsNum = Number(row.goodsNum);
      const stock = Number(row.stock);
      if (isNaN(goodsNum)) {
        alert("请输入数字");
        row.goodsNum = ''; // 清空无效输入
        return;
      }

      if (goodsNum <= 0) {
        alert("调拨数量必须大于0");
        row.goodsNum = ''; // 清空无效输入
        return;
      }

      if (goodsNum > stock) {
        alert("调拨数量不能超过库存数量");
        row.goodsNum = ''; // 清空无效输入
        return;
      }

      // 校验通过
      row.validationError = '';
    },
  //选择调出仓库后删除调入仓库对应
  chooseOutHouse() {
    this.detailList = [];
    this.form.houseInId = '';
    this.houseInList = this.houseOutList;
    this.houseInList = this.houseInList.filter(item => item.id !== this.form.houseOutId);
  },
  //获取所有仓库
  getAllHouseList() {
    getAllHouseList().then(response => {
      this.houseInList = response.data;
      this.houseOutList = response.data;
    })
  },
  //添加调拨单
  add() {
    if (this.form.detailList == '') {
      alert("请先选择调拨商品");
    }

    console.log(this.form);
    addTransfer(this.form).then(res => {
      alert(res.msg);
    })
  },
  /** 查询调拨管理列表 */
  getList() {
    this.loading = true;
    this.queryParams.params = {};
    if (null != this.daterangeModifyDate && '' != this.daterangeModifyDate) {
      this.queryParams.params["beginModifyDate"] = this.daterangeModifyDate[0];
      this.queryParams.params["endModifyDate"] = this.daterangeModifyDate[1];
    }
    listTransfer(this.queryParams).then(response => {
      this.transferList = response.rows;
      this.total = response.total;
      this.loading = false;
    });
  },
  // 取消按钮
  cancel() {
    this.selectedGoods = [];
    this.goodsList = [];
    this.goodsTotal = 0
    this.isGoodsList = false;
    this.detailList = [];
    this.open = false;
    this.reset();
  },
  // 表单重置
  reset() {
    this.form = {
      id: null,
      transferCode: null,
      houseOutId: null,
      houseInId: null,
      createBy: null,
      createDate: null,
      modifyBy: null,
      modifyDate: null,
      isDel: null,
      detailList: []
    };
    this.resetForm("form");
  },
  /** 搜索按钮操作 */
  handleQuery() {
    this.queryParams.pageNum = 1;
    this.getList();
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.daterangeModifyDate = [];
    this.resetForm("queryForm");
    this.handleQuery();
  },
  getGoodsIds(selection) {
    this.selectedGoods = selection;
  },
  // 多选框选中数据
  handleSelectionChange(selection) {
    this.ids = selection.map(item => item.id)
    this.single = selection.length !== 1
    this.multiple = !selection.length
  },
  /** 新增按钮操作 */
  handleAdd() {
    this.reset();
    this.open = true;
    this.title = "添加调拨单";
    this.getAllHouseList();
  },
  //将商品放入到调拨详情中
  adddetailList() {
    const newSelectedGoods = [];

    // 遍历当前选中的商品
    this.selectedGoods.forEach(item => {
      // 检查 detailList 中是否已经存在该商品
      if (!this.form.detailList.some(detailItem => detailItem.id === item.id)) {
        // 如果不存在，则添加到新数组中
        newSelectedGoods.push(item);
      }
    });

    // 将新数组中的商品合并到 detailList 中
    this.form.detailList = [...this.form.detailList, ...newSelectedGoods];
    console.log(this.form.detailList)
    // 关闭对话框
    this.isGoodsList = false;
  },
  removeGoods(index) {
    // 从 detailList 中移除指定索引的商品
    this.detailList.splice(index, 1);
  },
  /** 删除按钮操作 */
  handleDelete(row) {
    const ids = row.id || this.ids;
    this.$modal.confirm('是否确认删除调拨管理编号为"' + ids + '"的数据项？').then(function () {
      return delTransfer(ids);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => { });
  },
  /** 导出按钮操作 */
  handleExport() {
    this.download('store/transfer/export', {
      ...this.queryParams
    }, `transfer_${new Date().getTime()}.xlsx`)
  }
}
};
</script>
<style>
.transfer-details-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
